package com.boot.auth.support.provider;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.boot.auth.support.LoginDTO;
import com.boot.framework.token.domain.LoginUser;
import com.boot.system.dto.SysRoleDTO;
import com.boot.system.dto.SysUserDTO;
import com.boot.system.fegin.SysRoleClient;
import com.boot.system.fegin.SysUserClient;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yangfan
 * @date 2023/12/24
 * @Description
 */
@Component("passwordLogin")
@RequiredArgsConstructor
public class PasswordAuthenticationProvider implements AuthenticationProvider {


    private final SysUserClient sysUserClient;

    private final SysRoleClient sysRoleClient;

    @Override
    public LoginUser verify(LoginDTO loginDTO) {
        SysUserDTO sysUser = sysUserClient.selectByUsername(loginDTO.getUsername()).getData();
        LoginUser loginUser = new LoginUser();

        String ciphertext = SaSecureUtil.aesEncrypt(sysUser.getSalt(), loginDTO.getPassword());
        if (!ciphertext.equals(sysUser.getPassword())) {
            return null;
        }
        loginUser.setId(sysUser.getUserId());
        loginUser.setUsername(sysUser.getUsername());
        List<SysRoleDTO> sysRole = sysRoleClient.selectByIds(StrUtil.split(sysUser.getRoleIds(), ",")).getData();
        Set<String> roles = sysRole.stream().map(SysRoleDTO::getRoleCode).collect(Collectors.toSet());
        loginUser.setRoles(roles);

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        UserAgent ua = UserAgentUtil.parse(request.getHeader(Header.USER_AGENT.toString()));

        loginUser.setBrowser(ua.getBrowser().toString());
        loginUser.setVersion(ua.getVersion());
        loginUser.setOs(ua.getOs().toString());
        loginUser.setPlatform(ua.getPlatform().toString());
        loginUser.setLoginIp(request.getRequestURI());
        return loginUser;
    }

    //// 定义秘钥和明文
    //String key = "123456";
    //String text = "Sa-Token 一个轻量级java权限认证框架";
    //
    //// 加密
    //String ciphertext = SaSecureUtil.aesEncrypt(key, text);
    //System.out.println("AES加密后：" + ciphertext);
    //
    //// 解密
    //String text2 = SaSecureUtil.aesDecrypt(key, ciphertext);
    //System.out.println("AES解密后：" + text2);

}
